<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/18
 * Time: 17:13
 */

class Order_Model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商家订单
     * @param $timestart
     * @param $timeend
     * @param $baseId
     */
    public function checkOrder($year, $month, $baseId)
    {
        $db = clone($this->db);

        // 当月第一天
        $first = sprintf("%d-%02d-01 00:00:00", $year, $month);
        $last = date("Y-m-d 23:59:59", strtotime($first . ' +1 month -1 day'));

        $q = $db->select('id, sn, userId, priceType, baseId, totalPrice, goodsPrice, expressPrice, payMode, payWay, compTime, payStatus, status')->get_where('user_order', [
            'compTime >= ' => $first,
            'compTime <= ' => $last,
            'baseId' => $baseId,
            'jiesuan' => 0
        ]);
        return $q->result_array();
    }

    /**
     * 下单
     * @param $data
     * @param $goods
     * @param $exp
     * @return array|bool
     */
    public function add($data, $goods, $exp)
    {
        if (empty($goods)) {
            return false;
        }

        $datas = [];
        $totalPrice = [];
        $expPrice = $exp['base'];
        foreach ($goods as $g) {
            $datas[$g['baseId']][] = $g;
            if (empty($totalPrice[$g['baseId']])) {
                $totalPrice[$g['baseId']] = $g['price'] * $g['num'];
            } else {
                $totalPrice[$g['baseId']] += $g['price'] * $g['num'];
            }
        }

        $uuid = sn();
        try {
            $orderDb = clone($this->db);
            $orderDb->trans_start();

            foreach ($datas as $baseid => $item) {
                $expItem = isset($expPrice[$baseid]) ? $expPrice[$baseid] : 0;
                $totalItem = isset($totalPrice[$baseid]) ? $totalPrice[$baseid] : 0;
                $info = [
                    'uuid' => $uuid,
                    'sn' => sn(),
                    'baseId' => $baseid,
                    'userId' => $data['userId'],
                    'priceType' => value($data, 'userType'),
                    'totalPrice' => $totalItem + $expItem,
                    'goodsPrice' => $totalItem,
                    'expressPrice' => $expItem,
                    'addressId' => $data['expressId'],
                    'balancePrice' => $data['balance'],
                    'integralPrice' => $data['integralPrice'],
                    'integral' => $data['integral'],
                    'voucherPrice' => $data['voucherPrice'],
                    'voucher' => $data['voucherId'],
                    'message' => $data['message'],
                    'created' => date('Y-m-d H:i:s'),
                    'payMode' => 'online',
                    'payWay' => 2,          // 2 微信支付
                    'payStatus' => $data['totalPrice'] == 0 ? 6 : 0,
                    'status' => $data['totalPrice'] == 0 ? 'Pending' : 'Unpaid'
                ];

                $orderDb->insert('user_order', $info);
                $orderId = $orderDb->insert_id();

                if (empty($orderId)) {
                    $this->setError('下单失败');
                    return false;
                }

                $goodsData = [];
                $goodsIds = [];
                foreach($item as $row) {
                    $goodsData[] = [
                        'orderId' => $orderId,
                        'goodsId' => $row['goodsId'],
                        'ruleId' => $row['ruleId'],
                        'num' => $row['num'],
                        'price' => $row['price']
                    ];
                    $goodsIds[] = $row['goodsId'];
                }

                $uogDb = clone($this->db);
                $uogDb->insert_batch('user_order_goods', $goodsData);

                // 更新 car 表
                if (empty($this->updateCar($info['userId'], $goodsIds))) {
                    $this->setError('下单失败');
                    return false;
                }
            }

            $orderDb->trans_complete();
            if ($orderDb->trans_status()) {
                @statIncr('wxOrders');
                // return array_merge($data, ['orderId' => $orderId]);
                return $uuid;
            }

        } catch (Exception $e) {
            $this->setError('下单失败');
        }

        return false;
    }

    public function updateCar($userId, $goods)
    {
        $db = clone($this->db);
        $db->where(['userId' => $userId, 'selected' => 1]);
        $db->where_in('goodsId', $goods);
        $db->delete('user_car');
        return $db->affected_rows();
    }

}